import { queryTreeListByLength } from '@/api/api';
import { getAction } from '@/api/manage'

export function getSexVal(id){
  let value = id === '0' ? '未知' : (id === '1' ? '男' : '女');
  return value;
}

export async function queryDepartTree(selectOptions){
  let treeList = await getQueryDepartTree();
  let personList = await loadData();
  return selectOptions.map(item => {
    if(item.type === '0'){
      //部门
      let treeList_ = treeList.filter(treeItem => {
        return treeItem.id === item.value;
      })
      return {
        ...item,
        ...treeList_?.[0],
        label: treeList_?.[0]?.title
      }
    }else if(item.type === '1'){
      //人员
      let personList_ = personList.filter(personItem => {
        return personItem.id === item.value;
      })
      return {
        ...item,
        ...personList_?.[0],
        label: personList_?.[0]?.username
      }
    }
  })
}

function getQueryDepartTree(){
  return new Promise((resolve, reject) => {
    queryTreeListByLength({orgCode:'A03'}).then((res) => {
      if(res.success){
        //将树转为一维数组
        let treeList = transtrateTree(res.result);
        resolve(treeList);
      }
    })
  })
}

//获取人员信息
function loadData() {
  return new Promise((resolve, reject) => {
    let params = {
      pageNo: 1,
      pageSize: 9999
    }
    getAction('/sys/user/queryUserComponentData', params).then(res=>{
      if (res.success) {
        let personList = res.result.records;
        resolve(personList);
      }
    })
  })
}

//将树转为一维数组
function transtrateTree(treeData){
  let result = [];
  function loop(treeData){
    result = [...result, ...treeData];
    for(let i=0; i<treeData.length; i++){
      if(treeData[i]?.children && treeData[i]?.children.length){
        loop(treeData[i]?.children);
      }
    }
  }
  loop(treeData);
  return result;
}
